<?php
/**
 * 模板文件基类.
 */
namespace Lib\Core;

class Template extends \Home {

    public $path;

    protected $resourcePath = '/Resource';

    protected $staticFileVersion;

    private $templateDir = 'Template';

    /**
     * 为模板分配一个变量.
     *
     * @param string $key 变量名称.
     * @param mixed  $val 变量值.
     *
     * @return void
     */
    public function assign($key, $val) {
        $this->$key = $val;
    }

    /**
     * 显示一个模板.
     *
     * @param string $tpl 模板文件.
	 * @throws \Lib\Exception\System
     * @return string
     */
    public function display($tpl) {
        extract((array) $this);
		$template = str_replace(array($this->templateDir . '/', '.tpl.php'), array('', ''), $tpl);
		$this->path = $template;
        $file = APP_DIR . '/' . $tpl;
        if (!is_readable($file)) {
            throw new \Lib\Exception\System('模板文件未找到:' . $file);
        }
        require $file;
    }

    /**
     * 添加JS.
     *
     * @param string|array $js js文件.
     *
     * @return void
     */
    public function addJs($js) {
		$version = $this->staticFileVersion;
        if (is_array($js)) {
            foreach ($js as $v) {
                echo '<script src="' . $this->resourcePath . '/' . $v . '?v=' . $version . '" type="text/javascript"></script>' . PHP_EOL;
            }
        } else {
            echo '<script src="' . $this->resourcePath . '/' . $js . '?v=' . $version . '" type="text/javascript"></script>' . PHP_EOL;
        }
    }

	public function setStaticFileVersion($version) {
		$this->staticFileVersion = $version;
	}

    /**
     * 添加css.
     *
     * @param string|array $css css文件.
     *
     * @return void
     */
    public function addCss($css) {
		$version = $this->staticFileVersion;
        if (is_array($css)) {
            foreach ($css as $v) {
                echo '<link rel="stylesheet" href="' . $this->resourcePath . '/' . $v . '?=' . $version . '">' . PHP_EOL;
            }
        } else {
            echo '<link rel="stylesheet" href="' . $this->resourcePath . '/' . $css . '?=' . $version . '">' . PHP_EOL;
        }
    }

    /**
     * 导入一个模板.
     *
     * @param $tpl 模板文件.
     *
     * @return string
     * @throws \Lib\Exception\System
     */
    public function import($tpl) {
        extract((array) $this);
        $file = APP_DIR . '/' . $this->templateDir . '/' . $tpl . '.tpl.php';
        if (!is_readable($file)) {
            throw new \Lib\Exception\System('模板文件未找到');
        }
        require $file;
    }

    /**
     * 设置资源文件路径
     *
     * @param $path
     */
    public function setResourcePath($path) {
        $this->resourcePath = $path;
    }

    public function setTemplateDir($dir) {
        $this->templateDir = $dir;
    }

}